<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  website
 */

class m_website_actions_block_AddNewPageAction extends m_backoffice_extends_FormModal
{
	public function execute()
	{
		$docId = $this->getRequestParameter("docId");
		$docLang = $this->getRequestParameter("docLang");
	
		$values = $this->getFormValues("form");
		
		$parentDoc = $this->getDocumentProvider()->getByUniqueId($docId, $docLang);
		
		$page = m_website_documents_Page::createNew()->setLang($docLang);

		if($parentDoc->getDocumentModel() != "modules_website/website")
		{
			$relManager = f_relation_Manager::getInstance();
			$menus = $relManager->getParentsByDocType($docId, array("modules_website/menu", "modules_website/website"), $docLang);
			$menus[] = $parentDoc;
			
			$url = "";

			foreach($menus as $menu)
			{
				if($menu->getDocumentModel() == "modules_website/website")
				{
					$website = $menu;
				}
				else
				{
					$url .= $menu->getLabel()."/";
				}
			}

			$page->setUrl(strtolower(f_core_Routing::formatStringForUrl($url)));
		}
		else
		{
			$website = $parentDoc;
		}

		$templates = m_website_services_PageService::getInstance()->getTemplates($this->getContextWebsite()->getTheme(), $this->getContext('currentWebsite'));
		
		if(isset($values))
		{
			$errors = $this->checkValues($values, $page);

			if(count($errors) > 0)
            {
				$errors["status"] = "failed";
            }
            else
			{
                $values["url"] = preg_replace("#/$#", "", $values["url"]);
                
				$errors["status"] = "success";
				$page	->setLabel($values["label"])
						->setAuthor($this->getUser())
						->setMetaTitle($values["label"])
						->setTemplate($values["template"])
						->setUrl("/".$values["url"])
						->setPublicationstatus("DRAFT")
						->setMenuLabel($values["label"])
						->setMenuHoverLabel($values["label"])
						->setVisibleInMenu(true)
                        ->setInSiteMap(true)
                        ->setIndexable(true)
						->setWebsiteId($website->getUniqueId())
						->save(false);
				
				if($parentDoc != $page)
				{
					$parentDoc->addPage($page)->save();
				}
			}
			
			$this->addToModel("errors", $errors);
			$this->addToModel("templates", $templates);
			$this->addToModel("parentDoc", $parentDoc);
			$this->addToModel("href", $this->getRequestParameter("href"));
			$this->addToModel("page", $page);
			$this->addToModel("values", $values);
			$this->addToModel("website", $website);
			
			$this->setView('success');		

		}
		else
		{
			$this->addToModel("parentDoc", $parentDoc);
			$this->addToModel("templates", $templates);
			$this->addToModel("page", $page);
			$this->addToModel("href", $this->getRequestParameter("href"));
			$this->addToModel("website", $website);
			$this->addToModel("values", array("label" => "", "url" => $page->getUrl()));			
			$this->setView('success');		
		}
		
	}	
	
	public function validate()
	{
		return $this->getUserContext()->hasRight(array("backoffice_accessBo", "website_Add"));
	}
		
	private function checkValues($formValues, $page)
	{
		$errors = array();

		if($formValues["label"] == "")
		{
			$errors["label"] = $this->getLocale('website.errors.required');
		}

        if(!preg_match("/^([a-zA-Z0-9\/.~_,-])*$/",$formValues["url"]))
        {
            $errors["url"] = $this->getLocale('website.errors.invalidUrlChar');
        }

        if(preg_match("/\/([0-9]+)\//", $formValues["url"]))
        {
            $errors["url"] = $this->getLocale('website.errors.invalidUrlFormat');
        }

        if(substr($formValues["url"],0, 1) == "/")
        {
            $errors["url"] = $this->getLocale('website.errors.invalidUrlBegin');
        }
		
		return $errors;
	}
}